// pages/my/scoreExchange/record/record.js
let app = getApp();

Page({
  data: {
    url: '',
    userId: null,
    records: [],        // 兑换记录
    loading: false,
    noMore: false
  },

  onLoad() {
    this.setData({
      url: app.globalData.url
    });

    const user = wx.getStorageSync('user');
    if (user && user.id) {
      this.setData({ userId: user.id });
      this.loadRecords();
    } else {
      wx.showToast({ title: '请先登录', icon: 'none' });
      setTimeout(() => {
        wx.navigateBack();
      }, 1000);
    }
  },

  // 加载兑换记录
  loadRecords() {
    if (this.data.loading || this.data.noMore) return;

    this.setData({ loading: true });

    wx.request({
      url: this.data.url + 'exchange',
      method: 'GET',
      data: {
        userId: this.data.userId
      },
      success: (res) => {
        if (res.data.code === 200) {
          const newRecords = res.data.data.map(r => ({
            id: r.id,
            goodsName: r.goodsName,
            goodsImage: r.goodsImage,
            points: r.points,
            createTime: this.formatTime(r.createTime)
          }));

          this.setData({
            records: [...this.data.records, ...newRecords],
            noMore: newRecords.length < 10  // 假设分页10条
          });
        } else {
          wx.showToast({ title: '加载失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  // 时间格式化
  formatTime(timeStr) {
    if (!timeStr) return '';
    return timeStr.replace('T', ' ').substring(0, 19);
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      records: [],
      noMore: false
    });
    this.loadRecords();
    wx.stopPullDownRefresh();
  },

  // 上拉加载（可扩展分页）
  onReachBottom() {
    // TODO：实现分页加载
    if (!this.data.noMore) {
      // 暂不实现分页，可后续扩展
    }
  }
});